package routers

import (
	"awesome/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func InitDevice() {

	Api.GET("/devices", func(c *gin.Context) {
		var devices *[]models.Device
		page := c.DefaultQuery("page", "0")
		pageInt, err := strconv.Atoi(page)
		if err != nil {
			pageInt = 0
		}
		size := c.DefaultQuery("size", "10")
		sizeInt, err := strconv.Atoi(size)
		if err != nil {
			pageInt = 0
		}
		offset := pageInt * sizeInt

		devices, _ = models.GetDeviceList(sizeInt, offset)
		c.JSONP(http.StatusOK, devices)
	})

	Api.GET("/device/:id", func(c *gin.Context) {
		id := c.Param("id")
		var device *models.Device
		var idu, err = strconv.ParseUint(id, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
			return
		}
		device, _ = models.GetDeviceByID(uint(idu))
		c.JSONP(http.StatusOK, device)
	})

	Api.PUT("/device", func(c *gin.Context) {
		var device *models.Device
		err := c.BindJSON(&device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		println(device)
		err = models.UpdateDevice(device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.JSONP(http.StatusOK, device)
	})

	Api.DELETE("/device", func(c *gin.Context) {
		var device *models.Device
		err := c.BindJSON(&device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		println(device)
		err = models.DeleteDevice(device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.JSONP(http.StatusOK, device)
	})

	Api.POST("/device", func(c *gin.Context) {
		var device *models.Device
		err := c.BindJSON(&device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		println(device)
		err = models.CreateUpdateDevice(device)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.JSONP(http.StatusOK, device)
	})
}
